# -*- coding: utf-8 -*-

from core.utils import render_to

from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404

from core.forms import AddressForm

from exams.models import SubjectParticipant, Professor

from student.models import Student

# This is an empty simple view, to avoid errors
@login_required
@render_to('core/simple_index.htm')
def simple_index(request):
  subjects = SubjectParticipant.objects.filter(student__user=request.user)
  return {"subjects":subjects}

@login_required
@render_to('core/profile.htm')
def profile(request):
  addressForm = AddressForm()
  return {"addressForm":addressForm}

@login_required
def search(request, model):
  """Searches through the database for instance of a model. It takes these parameters via POST (mind the order!):
 
   * query - A search query, if comprised only of digits, it's going to do a pk search, otherwise it's going to
     go through first and last name - note, digit mode behaviour depends on the model
   * last_item - 0-indexed number to go on from (for "pagination")
  """
  items_per_page = 100
  
  if request.is_ajax() is False:
    raise Http404('Ta stran ne obstaja')
  
  last_item = int(request.POST.get('last_item', 0))
  query = request.POST.get('query', None)
  if query is None or query == '':
    # No, you shall not see all students
    return HttpResponse('[]', mimetype = 'application/json')
  
  # This has to be very general... (That's why the ifs)
  if model == 'student':
    output = Student.objects.all()
    if query.isdigit() is False:
      # Do we have first and last name?
      if ' ' in query:
        splited = query.split(' ')
        first_name = splited[1]
        last_name = splited[0]
      else:
        first_name = None
        last_name = query
      
      output = output.filter(user__last_name__istartswith = last_name)
      if first_name is not None:
        output = output.filter(user__first_name__istartswith = first_name)
    else:
      output = output.filter(enrollment_number__startswith = query)
  elif model == 'professor':
    output = Professor.objects.all()
    if query.isdigit() is False:
      # Do we have first and last name?
      if ' ' in query:
        splited = query.split(' ')
        first_name = splited[1]
        last_name = splited[0]
      else:
        first_name = None
        last_name = query
      
      output = output.filter(user__last_name__istartswith = last_name)
      if first_name is not None:
        output = output.filter(user__first_name__istartswith = first_name)
    else:
      output = output.filter(code__startswith = query)
  else:
    raise Http404('')
  
  sorting = request.POST.get('sorting_field', None)
  if sorting is not None and request.POST.get('sorting_order', None) is not None:
    output = output.order_by(('' if request.POST['sorting_order'] == 'asc' else '-') + request.POST['sorting_field'])
  
  json_serializer = serializers.get_serializer('json')()
  output = json_serializer.serialize(output[last_item:last_item + items_per_page], ensure_ascii = True, relations = ('user',))
  
  return HttpResponse(output, mimetype = 'application/json')

@login_required
def get_instance(request, model, pk):
  """Returns an instance of a model.
  """
  if request.is_ajax() is False:
    raise Http404('Ta stran ne obstaja')
  
  if model == 'student':
    instance = get_object_or_404(Student, pk = pk)
    relations = ('user', 'latest_enrollment_sheet',)
  elif model == 'professor':
    instance = get_object_or_404(Professor, pk = pk)
    relations = ('user',)
  else:
    raise Http404('')
  
  json_serializer = serializers.get_serializer('json')()
  output = json_serializer.serialize([instance], ensure_ascii = True, relations = relations)
  
  return HttpResponse(output, mimetype = 'application/json')
